package com.xqboss.apps.service.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.user.UserPushBind;
import com.xqboss.apps.mapper.user.UserPushBindMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserPushBindService extends ServiceImpl<UserPushBindMapper, UserPushBind> {

    /**
     * 绑定用户推送ID
     * @param userId
     * @param registrationId
     */
    public void bindUserPushId(Long userId, String registrationId){
        // 获取registerId之前绑定的用户，
        // 如果有，而且不是当前用户，则取消绑定之前的用户
        List<UserPushBind> list = list(new LambdaQueryWrapper<UserPushBind>()
                .eq(UserPushBind::getRegistrationId, registrationId));
        boolean isBindSelf = false;
        if(!list.isEmpty()){
            List<Long> removeIds = new ArrayList<>();
            for (UserPushBind bind : list) {
                if(!Objects.equals(bind.getUserId(), userId)){
                    removeIds.add(bind.getId());
                }else{
                    isBindSelf = true;
                }
            }
            if(!removeIds.isEmpty()){
                removeByIds(removeIds);
            }
        }
        if(!isBindSelf){
            UserPushBind bind = new UserPushBind();
            bind.setUserId(userId);
            bind.setRegistrationId(registrationId);
            save(bind);
        }
    }

    /**
     * 取消绑定推送ID
     * @param userId
     */
    public void unbindPushId(Long userId){
        remove(new LambdaQueryWrapper<UserPushBind>()
                .eq(UserPushBind::getUserId, userId));
    }


    /**
     * 获取用户推送Id
     * @param userId
     */
    public String getUserPushId(Long userId){
        UserPushBind bind = getOne(new LambdaQueryWrapper<UserPushBind>()
                .eq(UserPushBind::getUserId, userId)
                .orderByDesc(UserPushBind::getId)
                .last("limit 1"));
        return bind == null ? null : bind.getRegistrationId();
    }
}
